package com.sxj.PDMS.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxj.PDMS.common.ErrorCode;
import com.sxj.PDMS.exception.BusinessException;
import com.sxj.PDMS.mapper.StudentMapper;
import com.sxj.PDMS.model.vo.ActivistApplicationInformationListVO;
import com.sxj.PDMS.model.vo.DevelopTheObjectApplicationInformationListVO;
import com.sxj.PDMS.model.vo.PagingQueryResponse;
import com.sxj.PDMS.model.entity.ActivistApplicationInformationList;
import com.sxj.PDMS.model.entity.Student;
import com.sxj.PDMS.service.ActivistApplicationInformationListService;
import com.sxj.PDMS.mapper.ActivistApplicationInformationListMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.text.ParseException;
import java.util.List;
import static com.sxj.PDMS.utils.VerifyUtil.changeDate;


/**
* @author 503c'j
* @description 针对表【activist_application_information_list(积极分子申请信息列表)】的数据库操作Service实现
* @createDate 2024-06-13 14:50:10
*/
@Service
@Slf4j
public class ActivistApplicationInformationListServiceImpl extends ServiceImpl<ActivistApplicationInformationListMapper, ActivistApplicationInformationList>
    implements ActivistApplicationInformationListService{

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ActivistApplicationInformationListMapper activistApplicationInformationListMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void registerActivistApplicationBatch(List<ActivistApplicationInformationList> list) {
        log.info("批量注册积极分子");
        list.forEach(activistApplicationInformationList -> {
            // 1. 校验
            if (StringUtils.isAnyBlank(activistApplicationInformationList.getStudentNumber(),
                    activistApplicationInformationList.getTrainPeople())
                    && activistApplicationInformationList.getTimeOfApplication() == null &&
                    activistApplicationInformationList.getBranchTime() == null &&
                    activistApplicationInformationList.getPromotionTime()==null&&
                    activistApplicationInformationList.getDateOfApplicationForPartyMembership()==null
            ) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
            }
            if (activistApplicationInformationList.getStudentNumber().length() != 10) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, activistApplicationInformationList.getStudentNumber() + "的学号有误");
            }
            synchronized (activistApplicationInformationList.getStudentNumber().intern()) {
                //在学生表里存在
                QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("student_number", activistApplicationInformationList.getStudentNumber());
                //todo:待优化
                long studentCount = studentMapper.selectCount(queryWrapper);

                if (studentCount <= 0) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, activistApplicationInformationList.getStudentNumber() + "的账号不存在");
                }
                Integer statue = studentMapper.selectOne(queryWrapper).getStatue();
                if(statue<2){
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, activistApplicationInformationList.getStudentNumber() + "不能越级");
                }
                if(statue>2){
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, activistApplicationInformationList.getStudentNumber() + "不能倒退");
                }
                //提交入党申请书的时间
                java.util.Date date =  studentMapper.selectById(activistApplicationInformationList.getStudentNumber())
                        .getTheDateOfSubmissionOfTheApplicationForPartyMembership();

                Date theDateOfSubmissionOfTheApplicationForPartyMembership = null;
                try {
                    theDateOfSubmissionOfTheApplicationForPartyMembership = changeDate(date);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }

                if(!theDateOfSubmissionOfTheApplicationForPartyMembership.equals(activistApplicationInformationList.getDateOfApplicationForPartyMembership()) ){
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, activistApplicationInformationList.getStudentNumber() + "的入党申请书提交日期有误");
                }

                // 在积极分子表里账户不能重复
                QueryWrapper<ActivistApplicationInformationList> queryWrapperActivist = new QueryWrapper<>();
                queryWrapperActivist.eq("student_number", activistApplicationInformationList.getStudentNumber());

                long activistApplicationCount = activistApplicationInformationListMapper.selectCount(queryWrapperActivist);

                if (activistApplicationCount > 0) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, activistApplicationInformationList.getStudentNumber() + "的账号已存在");
                }

                // 2. 插入数据
                int inserted = activistApplicationInformationListMapper.insert(activistApplicationInformationList);
                if (inserted < 0) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
                }
                Student student = new Student();
                student.setStudentNumber(activistApplicationInformationList.getStudentNumber());
                // todo 用常量代替
                student.setStatue(3);
                studentMapper.updateById(student);
            }
        });
    }

    @Override
    public PagingQueryResponse<ActivistApplicationInformationListVO> selectAll(Integer page, Integer pageSize) {
        Integer start = (page - 1) * pageSize;
        List<ActivistApplicationInformationListVO> activistApplicationInformationLists = activistApplicationInformationListMapper.selectAll(start, pageSize);
        Long total = activistApplicationInformationListMapper.selectTotal();
        PagingQueryResponse<ActivistApplicationInformationListVO> pagingQueryResponse = new PagingQueryResponse<>();

        pagingQueryResponse.setRows(activistApplicationInformationLists);

        pagingQueryResponse.setTotal(total);

        return pagingQueryResponse;
    }

    @Override
    public PagingQueryResponse<ActivistApplicationInformationListVO> activistApplicationInformationList(Integer page, Integer pageSize,String studentNumber,String name) {
        Integer start = (page - 1) * pageSize;

        List<ActivistApplicationInformationListVO> activistApplicationInformationLists = activistApplicationInformationListMapper.selectByNumberOrName(start, pageSize,studentNumber, name);
        Long total = activistApplicationInformationListMapper.selectTotalByNumberOrName(studentNumber, name);

        PagingQueryResponse<ActivistApplicationInformationListVO> pagingQueryResponse = new PagingQueryResponse<>();
        pagingQueryResponse.setRows(activistApplicationInformationLists);
        pagingQueryResponse.setTotal(total);

        return pagingQueryResponse;



    }

    @Override
    public void selectAllStudentAndDownload(String studentNumber, String name, HttpServletResponse response) {
        List<ActivistApplicationInformationListVO> activistApplicationInformationListVOList = activistApplicationInformationListMapper.selectAllStudentAndDownload(studentNumber,name);
        log.info("查询结果列表大小: " + (activistApplicationInformationListVOList != null ? activistApplicationInformationListVOList.size() : "null"));

        if (activistApplicationInformationListVOList == null || activistApplicationInformationListVOList.isEmpty()) {
            log.error("没有符合条件的学生，将抛出异常");
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "没有符合条件的学生");
        }
        // 2.通过POI将数据写入template/积极分子基本信息表.xlsx文件
        InputStream stream = this.getClass().getClassLoader().getResourceAsStream("template/积极分子基本信息表.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(stream);

            // 填充数据
            for (int i = 0; i < activistApplicationInformationListVOList.size(); i++) {
                XSSFSheet sheet = excel.getSheetAt(0);
                // 获取第i+1行
                XSSFRow row = sheet.createRow(i + 2);
                ActivistApplicationInformationListVO activistApplicationInformationListVO = activistApplicationInformationListVOList.get(i);
                row.createCell(0).setCellValue(activistApplicationInformationListVO.getSerialNumber());
                row.createCell(1).setCellValue(activistApplicationInformationListVO.getStudentNumber());
                row.createCell(2).setCellValue(activistApplicationInformationListVO.getGrade());
                row.createCell(3).setCellValue(activistApplicationInformationListVO.getName());
                row.createCell(4).setCellValue(activistApplicationInformationListVO.getDateOfApplicationForPartyMembership());
                row.createCell(6).setCellValue(activistApplicationInformationListVO.getTimeOfApplication());
                row.createCell(7).setCellValue(activistApplicationInformationListVO.getBranchTime());
            }

            XSSFSheet sheet = excel.getSheetAt(0);
            XSSFRow row = sheet.createRow(activistApplicationInformationListVOList.size() + 2);
            row.createCell(0).setCellValue("下载时间:" + new java.util.Date().toString());


            // 3.通过输出流将文件下载到浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            excel.write(outputStream);

            // 4.关闭资源
            excel.close();
            outputStream.close();

            log.info("积极分子基本信息表.xlsx下载成功");

        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件下载失败");
        }
    }
}




